package com.vrv.common.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 汉字转拼音、ASCII码
 * 
 * @author 曹保利
 */
public class PinyinConvert {

	/**
	 * 将汉字转换为全拼
	 */
	public static String getPinYin(String src) {
		char[] srcCharArray = src.toCharArray();
		int length = srcCharArray.length;
		String[] t2 = new String[length];
		// 设置汉字拼音输出的格式
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_V);
		String result = "";
		try {
			for (int i = 0; i < length; i++) {
				// 判断是否为汉字字符
				// System.out.println(t1[i]);
				if (Character.toString(srcCharArray[i]).matches("[\\u4E00-\\u9FA5]+")) {
					t2 = PinyinHelper.toHanyuPinyinStringArray(srcCharArray[i], format);// 将汉字的几种全拼都存到t2数组中
					result += t2[0];// 取出该汉字全拼的第一种读音并连接到字符串t4后
				} else {
					// 如果不是汉字字符，直接取出字符并连接到字符串t4后
					result += Character.toString(srcCharArray[i]);
				}
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 提取每个汉字的首字母
	 * 
	 * @param str
	 * @return String
	 */
	public static String getPinYinHeadChar(String str) {
		String headChar = "";
		for (int j = 0; j < str.length(); j++) {
			char word = str.charAt(j);

			// 提取汉字的首字母
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
			if (pinyinArray != null) { // word 不为汉字
				headChar += pinyinArray[0].charAt(0);
			} else {
				headChar += word;
			}

		}
		return headChar;
	}

	/**
	 * 将字符串转换成ASCII码
	 * 
	 * @param cnStr
	 * @return String
	 */
	public static String getCnASCII(String cnStr) {

		StringBuffer strBuf = new StringBuffer();

		// 将字符串转换成字节序列
		byte[] bGBK = cnStr.getBytes();
		for (int i = 0; i < bGBK.length; i++) {
			// System.out.println(Integer.toHexString(bGBK[i] & 0xff));
			// 将每个字符转换成ASCII码
			strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
		}

		return strBuf.toString();
	}

	public static void main(String[] args) {
		String cnStr = "中华人99民共和国";
		System.out.println(getPinYin(cnStr));
		System.out.println(getPinYinHeadChar(cnStr));
		// System.out.println(getCnASCII(cnStr));
	}
}
